<?php
namespace app\api\controller;
use think\exception\HttpResponseException;
use think\Cache;
use think\Request;
use think\Response;

class Api
{

    protected $request;
    protected $params;

    protected $code = 200;
    protected $format = 'json';
    protected $options = [];

    protected $limit;
    protected $page;

    public function __construct() {
        $this->request = Request::instance();
        $this->params = $this->request->param();

        $this->limit = (isset($this->params['limit']) && is_numeric($this->params['limit'])) ? (int) $this->params['limit'] : 12;
        $this->page = (isset($this->params['page']) && is_numeric($this->params['page'])) ? max(1, $this->params['page']) : false;
        config('database.datetime_format', 'Y-m-d H:i:s');
        $this->_initialize();


    }


    protected function _initialize()
    {
        $formats = ['xml', 'json', 'jsonp'];
        $this->params['format'] = strtolower($this->params['format']);
        $this->format = in_array($this->params['format'], $formats) ? $this->params['format'] : $this->format;

        if(!$this->params['timestamp'] || $this->params['timestamp'] - time() > 30) {
//            return $this->response('请求已过期', [], -99999);
        }
    }

    /**
     * 输出返回数据
     * @param string $message 提示内容
     * @param array $result 返回数据
     * @param int $code HTTP状态码
     */
    protected function response($message, $result = [], $code = 200)
    {
        header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求
        $data = [
            'code'    => $code,
            'message' => $message,
            'result'  => $result,
        ];
        switch ($this->format) {
            case 'xml':
                $this->options['root_node'] = 'root';
                break;
            default:
                # code...
                break;
        }

        $response = Response::create($data, $this->format)
            ->options($this->options)
            ->code($this->code);
        throw new HttpResponseException($response);

    }

}
